/*
 * socket.c
 *
 *  Created on: 2009-5-28
 *      Author: root
 */

#include"mysocket.h"
#include"msgtype.h"
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>

#define FILE_MODE 0777

int socket(){
	static int i=0;
	int rv;
	msg message;
	sockmsg retmsg;
	memset(&message,0,sizeof(msg));
	memset(&retmsg,0,sizeof(sockmsg));
	message.mtype=MSG_USR_SOCK;
	message.pid=getpid();
	/*do{
		sprintf(message.buf,"/tmp/fifo%ld%d",(long)(message.pid),i++);
		rv=mkfifo(message.buf,FILE_MODE);
		if(rv<0&&errno!=EEXIST){
			fprintf(stderr,"can not create fifo in socket\n");
			return -1;
		}
	}while(rv<0&&errno==EEXIST);
	int fd=open(message.buf,O_RDONLY|O_NONBLOCK);
	//int fd=open(message.buf,O_RDWR);
	if(fd<0)
		return -1;*/
	message.msgqid=processqid;
	message.sock=++i;
	while(sockbuf[message.sock]!=NULL&&message.sock<MAXSOCKET){
		message.sock=++i;
	}
	if(message.sock==MAXSOCKET){
		return -1;
	}
	sockbuf[message.sock]=malloc(BUFLEN);
	memset(sockbuf[message.sock],0,BUFLEN);
	if(msgsnd(tcpipstackqid,&message,sizeof(msg)-sizeof(long),IPC_NOWAIT)<0){
		fprintf(stderr,"can not comunicate with tcp/ip stack\n");
		return -1;
	}
	if((rv=msgrcv(processqid,&retmsg,sizeof(sockmsg)-sizeof(long),message.sock,0))<0){
		fprintf(stderr,"tcp/ip stack does not work!\n");
		return -1;
	}
	return retmsg.ret;
}
